<template>
  <div>
    <div v-if="isPageLoading" class="page_loading fixed">
      <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
    </div>
    <header>
      <van-nav-bar class="main_header notice_header" :title="title">
        <template #left>
          <span @click="goBack">返回</span>
        </template>
      </van-nav-bar>
    </header>
    <div class="gl_padding_15">
      <div v-for="ktem in imgList" :key="ktem.id" class="box gl_mr_15 gl_mb_15" style="position: relative;">
        <img :src="getStaticFileUrl(ktem.fileDir)" width="80px">
        <div class="van-uploader__preview-delete" @click="remove(ktem.id)">
          <i class="van-icon van-icon-cross van-uploader__preview-delete-icon" />
        </div>
      </div>
      <div v-for="(item, index) in fileList" :key="index" class="box gl_mr_15 gl_mb_15">
        <img :src="getStaticFileUrl(item)" width="80px">
      </div>
      <van-uploader :after-read="submit" style="vertical-align: top;" />
    </div>
    <div class="bu_box">
      <van-button :loading="buLoading" style="width:100%; border-radius: 6px;" size="small" type="info" @click="submitData()">确 定</van-button>
    </div>
  </div>
</template>

<script>
import {
  api_GET_EventsManagementComRegisterFileCompetitionEntryFileByRegisterCompetitorRegisterId, // 查询体检资料
  api_POST_EventsManagementComRegisterFile, // 添加体检资料
  api_DELETE_EventsManagementComRegisterFileId // 删除体检资料
} from '@/extend/api/gameswaggerApi/app.js';
import {
  SiSTKWEventsManagementCreateCompetitionRegisterFileInput // 添加体检资料
} from '@/lib/form/game/swaggerForm';
import { getToken } from '@/lib/auth';
import axios from 'axios';
export default {
  data() {
    return {
      title: '资料上传',
      isPageLoading: false,
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      SiSTKWEventsManagementCreateCompetitionRegisterFileInput: new SiSTKWEventsManagementCreateCompetitionRegisterFileInput(),
      file: '',
      fileList: [],
      imgList: [],
      tokenInfo: getToken(),
      buLoading: false
    };
  },
  created() {
    this.gameId = this.$route.params.id;
    this.getData();
  },
  methods: {
    getData() {
      this.isPageLoading = true;
      const competitorRegisterId = this.$route.query.registerId;
      api_GET_EventsManagementComRegisterFileCompetitionEntryFileByRegisterCompetitorRegisterId(competitorRegisterId).then(res => {
        this.imgList = res;
        this.isPageLoading = false;
      }).catch(() => {
        this.isPageLoading = false;
      });
    },
    check(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$notify({ type: 'error', message: '上传图片只能是 JPG或者PNG 格式!' });
      }
      if (!isLt2M) {
        this.$notify({ type: 'error', message: '图片大小不能超过 5MB!' });
      }
      return isJPG && isLt2M;
    },
    // 上传图片
    upload() {
      return new Promise((resolve, reject) => {
        if (!this.file) {
          resolve('');
          return;
        }
        const form = new FormData();
        form.append('formFile', this.file);
        this.uploadApi(this.action, form).then(res => {
          if (res.status === 200) {
            this.fileList.push(res.data.tempUrl);
            console.log(this.fileList);
            resolve(res.data);
          } else {
            reject(res.data);
          }
        });
      });
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, file, config);
    },
    goBack() {
      this.$router.push({
        path: `/myCenter${this.gameId && '/' + this.gameId || ''}/entry/detail`,
        query: {
          id: this.$route.query.id
        }
      });
    },
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    submit(file) {
      const checkData = this.check(file.file);
      if (checkData) {
        this.file = file.file;
        this.upload();
      }
    },
    // 删除体检资料
    remove(id) {
      var that = this;
      that.$dialog.confirm({
        message: '您确定要删除吗？'
      }).then(() => {
        that.isPageLoading = true;
        api_DELETE_EventsManagementComRegisterFileId(id).then(res => {
          that.isPageLoading = false;
          this.$notify({ type: 'success', message: '删除成功' });
          that.getData(this.id);
        }).catch(() => {
          that.isPageLoading = false;
          this.$notify({ type: 'error', message: '删除失败' });
        });
      }).catch(() => {
        that.$notify({ type: 'primary', message: '取消删除' });
      });
    },
    submitData() {
      this.buLoading = true;
      this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput.competitionId = this.$route.query.id;
      this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput.competitorRegisterId = this.$route.query.registerId;
      this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput.fileDirs = this.fileList;
      api_POST_EventsManagementComRegisterFile(this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput).then(res => {
        this.buLoading = false;
        this.dialogVisible = false;
        this.fileList = [];
        this.$notify({ type: 'success', message: '上传成功' });
        this.getData();
      }).catch(() => {
        this.buLoading = false;
        this.dialogVisible = false;
        this.fileList = [];
        this.$notify({ type: 'error', message: '上传失败' });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.bu_box {
  width: 88%;
  position: fixed;
  bottom: 20px;
  left: 6%;
}
.box {
  width: 80px;
  height: 80px;
  display: inline-block;
}
</style>
